package 力扣日常刷题.木23一月.第08天308;

/**
 * @author 帅小伙
 * @date 2022/3/8
 * @description
 */
public class Demo14蜡烛之间的盘子 {

    public static void main(String[] args) {
        platesBetweenCandles("**|**|***|",new int[][]{{2,5},{5,9}});
    }

    public int[]  platesBetweenCandles1(String s,int[][] queries) {
        int sum = 0;
        int n = s.length();
        int[] preSum = new int[n];

        for (int i = 0; i < n; i++) {
            if(s.charAt(i) == '*')sum++;
            preSum[i] = sum;
        }

        int[] left = new int[n];
        for (int i = 0,l = -1; i < n; i++) {
            if(s.charAt(i) == '|')l = i;
            left[i] = l;
        }
        int[] right = new int[n];
        for (int i = n - 1, r = n - 1; i >= 0; i--) {
            if(s.charAt(i) == '|')r = i;
            right[i] = r;
        }

        int[] ans = new int[queries.length];
        for (int i = 0; i < ans.length; i++) {
            int x = right[queries[i][0]],y = left[queries[i][1]];
            ans[i] = x == -1 || y == -1 || x >= y ? 0 : preSum[y] - preSum[x];
        }
        return ans;
    }

    public static int[] platesBetweenCandles(String s, int[][] queries) {
        int n = s.length();
        int[] preSum = new int[n];

        for (int i = 0,sum = 0; i < n; i++) {
            if(s.charAt(i) == '*') sum++;
            preSum[i] = sum;
        }

        int[] left = new int[n];
        for (int i = 0,l = -1; i < n; i++) {
            if(s.charAt(i) == '|') {
                l = i;
            }
            left[i] = l;
        }
        int[]right = new int[n];
        for (int i = n - 1,r = n - 1; i >= 0; i--) {
            if(s.charAt(i) == '|') r = i;
            right[i] = r;
        }
        int[] ans = new int[queries.length];
        for (int i = 0; i < queries.length; i++) {
            int[] query = queries[i];
            int x = right[query[0]],y = left[query[1]];
            ans[i] = x == -1 || y == -1 || x >= y ? 0 : preSum[y] - preSum[x];
        }
        return ans;
    }

}
